﻿@page "/Structure"
@using iOSClub.Data
@using iOSClub.WebSite.Models
@using Markdig
@using Markdig.Syntax
@using Microsoft.EntityFrameworkCore
@inject IDbContextFactory<iOSContext> Factory

<PageTitle>社团结构 - 西建大iOS Club</PageTitle>

<Breadcrumb Style="margin-bottom: 10px" Class="desktop-phone">
    <BreadcrumbItem>
        <a href="/About">社团简介</a>
    </BreadcrumbItem>
    <BreadcrumbItem>
        <a href="/Structure">社团结构</a>
    </BreadcrumbItem>
</Breadcrumb>

<GridRow>
    <GridCol Xs="24" Sm="24" Md="20" Lg="20" Xl="20" Xxl="20">
        <MarkdownRenderer html="@Content"/>
    </GridCol>
    <GridCol Md="4" Lg="4" Xl="4" Xxl="4" Class="desktop-phone">
        <Affix>
            <Anchor>
                @foreach (var s in Anchors)
                {
                    <AnchorLink Href="@s.Link" Title="@s.Name"/>
                }
            </Anchor>
        </Affix>
    </GridCol>
</GridRow>

@code {
    private string Content { get; set; } = "";
    private List<MarkAnchorModel> Anchors { get; } = [];

    protected override async Task OnParametersSetAsync()
    {
        await using var db = await Factory.CreateDbContextAsync();
        var article = await db.Articles.AsNoTracking().FirstOrDefaultAsync(x => x.Path == "Structure");
        if (article is null) return;
        Content = article.Content;

        // 强制更新UI
        StateHasChanged();

        // 延迟解析锚点以提升首次渲染速度
        await ParseAnchorsAsync(Content);
    }

    private async Task ParseAnchorsAsync(string content)
    {
        var pipeline = new MarkdownPipelineBuilder().Build();
        var document = Markdown.Parse(content, pipeline);
        var count = 0;
        Anchors.Clear();
        await document.ForEachAsync(x =>
        {
            if (x is not HeadingBlock { Inline: not null } headingBlock)
                return Task.CompletedTask;

            count++;
            if (count == 1) return Task.CompletedTask;
            
            var id = headingBlock.Inline.FirstChild?.ToString() ?? Guid.NewGuid().ToString();
            
            Anchors.Add(new MarkAnchorModel
            {
                Name = id,
                Link = $"/About#{id}"
            });

            return Task.CompletedTask;
        });
        
        // 更新锚点后再次刷新
        StateHasChanged();
    }

}